package socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class Server {
    private ServerSocket serverSocket;
    public Server(){
        try {
            System.out.println("启动服务器");
            serverSocket=new ServerSocket(8010);
            System.out.println("服务器启动完毕");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start(){
        try {
            while (true){
                System.out.println("服务器等待连接");
                Socket socket=serverSocket.accept();
                System.out.println("已连接一个服务器");
                CilntHandler handler=new CilntHandler(socket);
                Thread t=new Thread(handler);
                t.start();

            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        Server server=new Server();
        server.start();
    }
   public class CilntHandler implements Runnable{
       private Socket socket;
       private String host;
       public CilntHandler(Socket socket){
           this.socket=socket;
           host=socket.getInetAddress().getHostAddress();//通过sockt访问客户端的ip地址
       }
        public void run(){
            try {
                InputStream is= socket.getInputStream();
                InputStreamReader isr=new InputStreamReader(is, StandardCharsets.UTF_8);
                BufferedReader br=new BufferedReader(isr);

                String line;
                while ((line=br.readLine())!=null){
                    System.out.println(host+"说:"+line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
   }
}
